<template>
  <div class="division-manage">
    <el-card class="login-form">
      <template #header>
        <div class="card-header">
          <span>行政区域管理</span>
          <div>
            <el-button type="primary" @click="handleAdd">添加区域</el-button>
          </div>
        </div>
      </template>

      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/" class="area-breadcrumb">
        <el-breadcrumb-item @click="goToLevel('county')" style="cursor:pointer;">全部县</el-breadcrumb-item>
        <el-breadcrumb-item v-if="selectedCounty" @click="goToLevel('town')" style="cursor:pointer;">{{ selectedCounty.name }}</el-breadcrumb-item>
        <el-breadcrumb-item v-if="selectedTown">{{ selectedTown.name }}</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 区域列表表格 -->
      <el-table
          :data="currentLevelData"
          border
          style="width: 100%"
          highlight-current-row>
        <el-table-column prop="code" label="行政编码" width="150" />
        <el-table-column prop="name" label="区域名称" width="200" />
        <el-table-column prop="level" label="级别" width="100">
          <template #default="scope">
            <el-tag :type="getLevelTagType(scope.row.level)">
              {{ levelText[scope.row.level] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上级区域" width="200">
          <template #default="scope">
            <span v-if="scope.row.level === 1">-</span>
            <span v-else>{{ scope.row.parentId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
                :disabled="(scope.row.level === 1 && townList.some(t => t.countyId === scope.row.id)) ||
                         (scope.row.level === 2 && villageList.some(v => v.townId === scope.row.id))">
              删除
            </el-button>
            <el-button size="small" type="primary" @click="handleView(scope.row)" v-if="scope.row.level !== 3">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑区域对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="`${isEdit ? '编辑' : '添加'}区域`"
        width="40%">
      <el-form :model="currentArea" label-width="100px">
        <el-form-item label="区域级别">
          <el-input :value="levelText[currentArea.level]" disabled />
        </el-form-item>
        <el-form-item label="行政编码" prop="code">
          <el-input v-model="currentArea.code" />
        </el-form-item>
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="currentArea.name" />
        </el-form-item>
        <el-form-item label="所属县" v-if="currentArea.level === 2 || currentArea.level === 3">
          <el-input :value="currentArea.countyId" disabled />
        </el-form-item>
        <el-form-item label="所属镇" v-if="currentArea.level === 3">
          <el-input :value="currentArea.townId" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitArea"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from 'axios';

const countyList = ref([]);
const townList = ref([]);
const villageList = ref([]);
const currentLevel = ref("county"); // county/town/village
const selectedCounty = ref(null);
const selectedTown = ref(null);
const dialogVisible = ref(false);
const isEdit = ref(false);
const currentArea = ref({
  id: 0,
  code: "",
  name: "",
  level: 1,
  parentId: null,
  countyId: null,
  townId: null
});

const levelText = { 1: "县", 2: "镇", 3: "村" };

const loadCountyList = async () => {
  const res = await axios.get('/division/list?level=1');
  if (res.data.code === 200) countyList.value = res.data.data;
};
const loadTownList = async (countyName) => {
  const res = await axios.get(`/division/list?level=2&parentId=${countyName}`);
  if (res.data.code === 200) townList.value = res.data.data;
};
const loadVillageList = async (townName) => {
  const res = await axios.get(`/division/list?level=3&parentId=${townName}`);
  if (res.data.code === 200) villageList.value = res.data.data;
};

const currentLevelData = computed(() => {
  if (currentLevel.value === "county") return countyList.value;
  if (currentLevel.value === "town") return townList.value;
  if (currentLevel.value === "village") return villageList.value;
  return [];
});

const getLevelTagType = (level) => {
  switch (level) {
    case 1: return "danger";
    case 2: return "warning";
    case 3: return "success";
    default: return "info";
  }
};

const handleView = (row) => {
  if (row.level === 1) {
    selectedCounty.value = row;
    selectedTown.value = null;
    currentLevel.value = "town";
    loadTownList(row.name);
  } else if (row.level === 2) {
    selectedTown.value = row;
    currentLevel.value = "village";
    loadVillageList(row.name);
  }
};

const goToLevel = (level) => {
  if (level === 'county') {
    currentLevel.value = 'county';
    selectedCounty.value = null;
    selectedTown.value = null;
    loadCountyList();
  } else if (level === 'town' && selectedCounty.value) {
    currentLevel.value = 'town';
    selectedTown.value = null;
    loadTownList(selectedCounty.value.name);
  }
};

const handleAdd = () => {
  isEdit.value = false;
  if (currentLevel.value === 'county') {
    currentArea.value = {
      id: 0,
      code: '',
      name: '',
      level: 1,
      parentId: null,
      countyId: null,
      townId: null
    };
  } else if (currentLevel.value === 'town' && selectedCounty.value) {
    currentArea.value = {
      id: 0,
      code: '',
      name: '',
      level: 2,
      parentId: selectedCounty.value.name,
      countyId: selectedCounty.value.name,
      townId: null
    };
  } else if (currentLevel.value === 'village' && selectedTown.value && selectedCounty.value) {
    currentArea.value = {
      id: 0,
      code: '',
      name: '',
      level: 3,
      parentId: selectedTown.value.name,
      countyId: selectedCounty.value.name,
      townId: selectedTown.value.name
    };
  }
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  isEdit.value = true;
  currentArea.value = { ...row };
  dialogVisible.value = true;
};

const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除该${levelText[row.level]} "${row.name}" 吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await axios.delete(`/division/delete/${row.id}`);
    if (res.data.code === 200) {
      ElMessage.success("删除成功");
      if (currentLevel.value === "county") loadCountyList();
      else if (currentLevel.value === "town") loadTownList(selectedCounty.value.name);
      else if (currentLevel.value === "village") loadVillageList(selectedTown.value.name);
    } else {
      ElMessage.error(res.data.message || "删除失败");
    }
  }).catch(() => {
    ElMessage.info("已取消删除");
  });
};

const submitArea = async () => {
  if (!currentArea.value.code || !currentArea.value.name || !currentArea.value.level) {
    ElMessage.error("请填写完整信息");
    return;
  }
  // 设置 parentId、countyId、townId
  if (currentArea.value.level === 1) {
    currentArea.value.parentId = null;
    currentArea.value.countyId = null;
    currentArea.value.townId = null;
  } else if (currentArea.value.level === 2) {
    currentArea.value.parentId = currentArea.value.countyId;
    currentArea.value.townId = null;
  } else if (currentArea.value.level === 3) {
    currentArea.value.parentId = currentArea.value.townId;
  }
  let url = '/division/add';
  let method = 'post';
  if (isEdit.value) {
    url = '/division/update';
    method = 'put';
  }
  const res = await axios[method](url, currentArea.value);
  if (res.data.code === 200) {
    ElMessage.success(isEdit.value ? "更新成功" : "添加成功");
    dialogVisible.value = false;
    loadCountyList();
    if (currentArea.value.level === 2) loadTownList(currentArea.value.countyId);
    if (currentArea.value.level === 3) loadVillageList(currentArea.value.townId);
  } else {
    ElMessage.error(res.data.message || "操作失败");
  }
};

onMounted(() => {
  loadCountyList();
});
</script>

<style scoped>
.division-manage {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-table {
  margin-top: 20px;
}

.el-table--enable-row-hover .el-table__body tr:hover>td {
  background-color: #f5f7fa;
  cursor: pointer;
}

.area-breadcrumb {
  margin-bottom: 20px;
  font-size: 16px;
}
</style>